package com.ptu.spzx.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ptu.spzx.common.exception.ptuException;
import com.ptu.spzx.domain.file.Dto.FileDTO;
import com.ptu.spzx.domain.file.File;


import com.ptu.spzx.mapper.FileMapper;
import com.ptu.spzx.model.vo.common.Result;
import com.ptu.spzx.model.vo.common.ResultCodeEnum;
import com.ptu.spzx.service.IFileService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author YT
 * @since 2024-01-28
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements IFileService {

    @Autowired
    private FileMapper fileMapper;

    String SAVE_EXAM_PATH="C:\\Users\\tan\\Desktop";
    @Override
    public Result upload(FileDTO fileDTO) throws IOException {
        MultipartFile file = fileDTO.getFile();
        // aaa.png
        String originalFilename=file.getOriginalFilename();//文件的原始名称

//         存储路径
        String filesPath = SAVE_EXAM_PATH;

        java.io.File parentFile = new java.io.File(filesPath);
        if(!parentFile.exists()){
//             如果文件父级目录不存在，就创建
            parentFile.mkdirs();
        }

//          要保存的文件目录
        java.io.File saveFile=new java.io.File(filesPath,originalFilename);
        if(saveFile.exists()){
//              如果当前上传的文件已经存在了，那么这个时候我就要重名一个文件名称
            originalFilename = System.currentTimeMillis() +"_"+originalFilename;
            saveFile=new java.io.File(filesPath , originalFilename);
        }
        file.transferTo(saveFile);
//保存文件地址到数据库
        File fileEntity = new File();
        fileEntity.setFileName(originalFilename);
        fileEntity.setFileUrl(saveFile.getPath());
        fileEntity.setCreateTime(LocalDateTime.now());
        fileEntity.setBelongExamId(fileDTO.getExamId());
        fileEntity.setStuId(fileDTO.getStuId().toString());
        fileMapper.insert(fileEntity);
        // 存储文件到本地的磁盘里面去
        String url="http://sc/exam/file/download/"+originalFilename;
        // 返回文件的链接就是文件的下载地址
        return Result.build( url,200,"success");
    }

    @Override
    public void download(String fileName, HttpServletResponse response) throws IOException {
        String filePath=SAVE_EXAM_PATH + java.io.File.separator + fileName;
        if (!FileUtil.exist(filePath)){
            throw new ptuException(ResultCodeEnum.DATA_EXIST);
        }
        byte[] bytes = FileUtil.readBytes(filePath);

        ServletOutputStream outputStream = response.getOutputStream();

        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }
}
